{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-09-16T11:10:59.098668Z",
     "start_time": "2025-09-16T11:10:59.095284Z"
    }
   },
   "source": [
    "import os\n",
    "import psutil\n",
    "import gc\n",
    "import objgraph\n",
    "\n",
    "# 垃圾回收\n",
    "def show_memory_info(hint):\n",
    "    pid = os.getpid()\n",
    "    p = psutil.Process(pid)\n",
    "\n",
    "    info = p.memory_full_info()\n",
    "    memory = info.uss / 1024. /1024\n",
    "    print('{} memory used: {} MB'.format(hint, memory))\n",
    "\n",
    "# def func():\n",
    "#     show_memory_info('initial')\n",
    "#     # global a\n",
    "#     a = [i for i in range(10000000)]\n",
    "#     show_memory_info('after a created')\n",
    "#     return a\n",
    "#\n",
    "# func()\n",
    "# show_memory_info('after a created')\n",
    "# import sys\n",
    "#\n",
    "# a = []\n",
    "#\n",
    "# # 两次引用，一次来自 a，一次来自 getrefcount\n",
    "# print(sys.getrefcount(a))\n",
    "#\n",
    "# def func(a):\n",
    "#     # 四次引用，a，python 的函数调用栈，函数参数，和 getrefcount\n",
    "#     print(sys.getrefcount(a))\n",
    "#\n",
    "# func(a)\n",
    "#\n",
    "# # 两次引用，一次来自 a，一次来自 getrefcount，函数 func 调用已经不存在\n",
    "# print(sys.getrefcount(a))\n",
    "# show_memory_info('initial')\n",
    "#\n",
    "# a = [i for i in range(10000000)]\n",
    "#\n",
    "# show_memory_info('after a created')\n",
    "#\n",
    "# # 清空地址a\n",
    "# del a\n",
    "# gc.collect()\n",
    "#\n",
    "# show_memory_info('finish')\n",
    "# print(a)\n",
    "# import gc\n",
    "# def func():\n",
    "#     show_memory_info('initial')\n",
    "#     a = [i for i in range(1000000)]\n",
    "#     b = [i for i in range(1000000)]\n",
    "#     show_memory_info('after a, b created')\n",
    "#     a.append(b)\n",
    "#     b.append(a)\n",
    "# func()\n",
    "# # 启动垃圾回收\n",
    "# gc.collect()\n",
    "# show_memory_info('after a, b created')\n",
    "# a = [1,2,3]\n",
    "# b = [4,5,6]\n",
    "# a.append(b)\n",
    "# b.append(a)\n",
    "# objgraph.show_backrefs([a])\n",
    "x = [1]\n",
    "x.append(x)\n",
    "print(len(x))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "execution_count": 14
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
